package com.starhub.application.rag.transformer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.starhub.application.rag.constant.RagConstant;
import com.starhub.application.rag.dto.SegmentDto;
import com.starhub.application.rag.service.SegmentService;
import com.starhub.utils.Util;

import dev.langchain4j.data.document.Metadata;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.data.segment.TextSegmentTransformer;

/**
 * 分段文本转换器, 切片在前置功能处理，这里只处理分段文本本身和元数据
 * 
 * @version: V1.0
 * @author: liuhf
 * @time 2025-06-05
 */
@Component
public class SimpleTextSegmentTransformer implements TextSegmentTransformer {

    @Autowired
    private SegmentService segmentService;

    /**
     * 分段文本转换器, 切片在前置功能处理，这里只处理分段文本本身和元数据
     * 
     * @param segment
     * @return
     */
    @Override
    public TextSegment transform(TextSegment segment) {
        Metadata metadata = segment.metadata();
        SegmentDto segmentDto = SegmentDto.builder()
                .segmentIndex(metadata.getInteger(RagConstant.EmbeddingMetaData.INDEX))
                .itemId(metadata.getString(RagConstant.EmbeddingMetaData.ITEM_ID))
                .collectionId(metadata.getString(RagConstant.EmbeddingMetaData.COLLECTION_ID))
                .baseId(metadata.getString(RagConstant.EmbeddingMetaData.BASE_ID))
                .segmentContent(segment.text())
                .segmentMetadata(metadata.toString())
                .build();

        Long id = segmentService.create(segmentDto);
        if (id == null) {
            throw new RuntimeException("分段失败" + segment);
        }

        segment.metadata().put(RagConstant.EmbeddingMetaData.SEGMENT_ID, Util.null2String(id));
        return segment;
    }

}
